#include "config.h"
#include <fstream>

namespace XIAOO{
    Config::Config(){
        
    }

    Config::~Config(){

    }

    void Config::initClientConfig(){
        if (this->clientConfig == false)
        {
            std::ifstream ifs;
            ifs.open("config/client_config.json", std::ios::binary);

            JSONCPP_STRING errs;
            Json::Value root, lang, mail;
            Json::CharReaderBuilder readerBuilder;
        
            std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
            bool res = Json::parseFromStream(readerBuilder, ifs, &this->clientConfig, &errs);
            if (!res || !errs.empty()) {
                ifs.close();
                printf("read config failed\r\n");
                exit(1);
            }

            ifs.close();

            std::string ip = this->clientConfig["server"]["ip"].asString();
            if(ip == ""){
                printf("config field 'server:ip' empty\r\n");
                exit(1);
            }
        }
    }

    void Config::initServerConfig(){
        if (this->serverConfig == false)
        {
            std::ifstream ifs;
            ifs.open("config/config.json", std::ios::binary);

            JSONCPP_STRING errs;
            Json::Value root, lang, mail;
            Json::CharReaderBuilder readerBuilder;
        
            std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
            bool res = Json::parseFromStream(readerBuilder, ifs, &this->serverConfig, &errs);
            if (!res || !errs.empty()) {
                ifs.close();
                printf("read config failed\r\n");
                exit(1);
            }

            ifs.close();

            std::string ip = this->serverConfig["server"]["ip"].asString();
            if(ip == ""){
                printf("config field 'server:ip' empty\r\n");
                exit(1);
            }

            std::string dbHost = this->serverConfig["db"]["host"].asString();
            if(dbHost == ""){
                printf("config field 'db:host' empty\r\n");
                exit(1);
            }
            
        }
    }

    Json::Value Config::readClientConfig(){
        this->initClientConfig();
        return this->clientConfig;
    }

    Json::Value Config::readServerConfig(){
        this->initServerConfig();
        return this->serverConfig;
    }
} 